package day04;

import lombok.Data;

import java.util.Scanner;

/*
@Author: 王少杰
@Date: 2025/1/3
@Time: 14:37
@FileName: Demo06.java
@描述:异常处理:
            Python:try except finally raise
            Java:  try catch finally throw throws
*/
public class Demo06 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入两个数字:");
        try {
            int a = sc.nextInt();
            int b = sc.nextInt();
            System.out.println(a / b);
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("异常信息为:" + e.getMessage());
        }finally {
            System.out.println("执行结束");
        }

        Demo05 demo05 = null; //代码有缺陷导致,需要解决缺陷，不能用try-catch隐藏此类问题
        if (demo05 != null) {
            demo05.chengfa(10,20);
        }
        //demo05.chengfa(10,20);//NullPointerException 最常见的异常--->空指针异常

        //Demo05[] demo05s = new Demo05[3];
        //System.out.println(demo05s[4]); //ArrayIndexOutOfBoundsException
    }
}

class Stu {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    /*
    throws：方法头中使用，声明抛出了一个异常。告诉调用者，方法使用时会有异常。
    throw:方法体中使用，抛出异常。
     */
    public void setAge(int age) throws Exception {
        if (age >= 7 && age <= 18) {
            this.age = age;
        }else {
            throw new Exception("输入的年龄不合法，必须在7~18之间");
        }
    }

    public static void main(String[] args) throws Exception {
        Stu student = new Stu();
        try {
            student.setAge(10);
            student.setAge(20);
        }catch (Exception e) {
            System.out.println("异常信息为:" + e.getMessage());
        }
    }
}